package com.zr.bookcorner.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.style.ReplacementSpan;

import androidx.annotation.NonNull;

import com.zr.bookcorner.BookApplication;

import okhttp3.internal.Util;

public class RoundBackgroundColorSpan extends ReplacementSpan {
    private int bgColor;
    private int textColor;

    public RoundBackgroundColorSpan(int bgColor) {
        super();
        this.bgColor = bgColor;
    }

    public RoundBackgroundColorSpan(int bgColor, int textColor) {
        super();
        this.bgColor = bgColor;
        this.textColor = textColor;
    }

    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        //设置宽度为文字宽度加16dp
//        return ((int)paint.measureText(text, start, end)+ Util.px2Dp(16));
        return (int) paint.measureText(text, start, end) + px2dp(10);
    }

    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
        int originalColor = paint.getColor();
        paint.setColor(this.bgColor);
        //画圆角矩形背景
        canvas.drawRoundRect(new RectF(x,
                        top,
                        x + ((int) paint.measureText(text, start, end)) + px2dp(10),
                        bottom),

                px2dp(8),
                px2dp(8),
                paint);
        paint.setColor(this.textColor);
        //画文字,两边各增加8dp
        canvas.drawText(text, start, end, x + px2dp(5), y, paint);
        //将paint复原
        paint.setColor(originalColor);
    }
    private     int px2dp( float pxValue){
         float scale= BookApplication.getContext().getResources().getDisplayMetrics().density;
        return (int)(pxValue/scale+0.5f);
    }
}
